import React, { Component } from 'react'
import {
  Text,
  View,
  Image,
  StyleSheet,
  Platform,
  PixelRatio,
  ScrollView,
  Dimensions,
  AlertIOS,
  StatusBar,
  Animated,
  RefreshControl,
  TouchableOpacity,
  TouchableWithoutFeedback,
  FlatList,
  Modal,
} from 'react-native'
import Immutable from 'immutable'
import Icon from 'react-native-vector-icons/Ionicons'
import Item from '../component/Item'
import FixHeader from '../component/FixHeader'
import RootView from '../component/RootView'
import Base from './Base'
import Search from './Search'
import { NavigationActions, createAction, px2dp, imageServer } from '../utils'
import * as categoryService from '../services/category'

const { width, height } = Dimensions.get('window')

const borderWidth = (Platform.OS === 'ios' ? 1.0 : 1.0) / PixelRatio.get()

const MAIN_HEIGHT = height - (Platform.OS === 'ios' ? 64 : 42) - 36
const LABEL_HEIGHT = 25
const PIC_SIZE = px2dp(60)

const cols = 3
const cellWH = 80
const vMargin = (width - 100 - cellWH * cols) / (cols + 1)
const hMargin = 25

class Category extends Base {
  constructor(props) {
    super(props)
    this.state = {
      activeIndex: 0,
      searchVisible: false,
      category: Immutable.List(),
      // flatlist不支持Immutable
      subcategory: [],
      notConnected: false,
    }
    this.navListener = null
  }
  openSearch() {
    this.setState({ searchVisible: true })
  }
  closeSearch() {
    this.setState({ searchVisible: false })
  }
  search(keywords) {
    const { navigation } = this.props
    const navigateAction = NavigationActions.navigate({
      routeName: 'GoodsList',
      params: { keywords },
    })
    this.closeSearch()
    navigation.dispatch(navigateAction)
  }
  async loadData() {
    const data = await categoryService.categoryA()
    // 获取第一条数据的子分类
    let subcategory = []
    if (data.length > 0) {
      const id = data[0].id
      subcategory = await categoryService.categoryB({ id })
    }
    this.setState({
      category: Immutable.fromJS(data),
      subcategory,
    })
  }
  loadCategoryB(index, id) {
    categoryService
      .categoryB({
        id,
      })
      .then(data => {
        this.setState({
          activeIndex: index,
          subcategory: data,
        })
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  renderTypes(items) {
    const activeIndex = this.state.activeIndex

    return (
      <View>
        {items.map((item, i) => (
          <TouchableOpacity
            key={i}
            onPress={() => {
              this.loadCategoryB(i, item.get('id'))
            }}
          >
            <View
              style={[styles.typeItem, i == activeIndex ? styles.active : null]}
            >
              <Text numberOfLines={2} style={{ color: '#666' }}>
                {item.get('name')}
              </Text>
            </View>
          </TouchableOpacity>
        ))}
      </View>
    )
  }
  renderList(data) {
    const _renderItem = ({ item }) => (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => this.goto('GoodsList', { caid: 0, cbid: item.id })}
      >
        <View style={styles.innerViewStyle}>
          <Image
            source={{ uri: imageServer + item.icon }}
            style={styles.iconStyle}
          />
          <Text style={{ color: 'gray', marginTop: 5 }}>{item.name}</Text>
        </View>
      </TouchableOpacity>
    )
    return (
      <FlatList
        numColumns={cols}
        horizontal={false}
        keyExtractor={(item, index) => index}
        data={data}
        renderItem={_renderItem}
      />
    )
  }
  componentWillUnmount() {
    this.navListener.remove()
  }
  componentDidMount() {
    this.navListener = this.props.navigation.addListener('didFocus', () => {
      StatusBar.setBarStyle('dark-content')
      // isAndroid && StatusBar.setBackgroundColor('#ecf0f1');
    })
    this.loadData()
    this.props.navigation.setParams({ openSearch: () => this.openSearch() })
  }
  render() {
    const { notConnected, fetching, msg, category, subcategory } = this.state

    return (
      <RootView
        notConnected={notConnected}
        fetching={fetching}
        style={styles.container}
      >
        <View style={{ width: px2dp(100), backgroundColor: '#f0f0f0' }}>
          <ScrollView style={{ paddingTop: 0 }}>
            {this.renderTypes(category)}
          </ScrollView>
        </View>
        <View style={{ flex: 1, backgroundColor: '#fff' }}>
          {this.renderList(subcategory)}
        </View>
        <Modal
          animationType={'slide'}
          transparent
          onRequestClose={() => {}}
          visible={this.state.searchVisible}
        >
          <Search
            onCancel={() => this.closeSearch()}
            onSearch={keywords => this.search(keywords)}
          />
        </Modal>
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
  },

  typeItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 15,
    paddingHorizontal: 10,
    borderBottomWidth: borderWidth,
    borderBottomColor: '#eee',
    backgroundColor: '#f0f0f0',
  },
  itemWrap: {
    paddingTop: 12,
    paddingBottom: 6,
    borderBottomWidth: borderWidth,
    borderBottomColor: '#f0f0f0',
    backgroundColor: '#f0f0f0',
    paddingHorizontal: 12,
  },
  item: {
    flexDirection: 'row',
  },
  label: {
    height: LABEL_HEIGHT,
    paddingLeft: 10,
    justifyContent: 'center',
    backgroundColor: '#f0f0f0',
    borderLeftWidth: 3,
    borderLeftColor: '#ddd',
  },
  active: {
    borderLeftWidth: 3,
    borderLeftColor: '#e23f3c',
    paddingLeft: 7,
    backgroundColor: '#fff',
    borderBottomColor: '#fff',
  },
  addBtn: {
    backgroundColor: 'transparent',
    position: 'absolute',
    right: 4,
    bottom: 4,
    width: 40,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },
  priceView: {
    flexDirection: 'row',
    backgroundColor: 'transparent',
    position: 'absolute',
    right: 34,
    bottom: 4,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },

  innerViewStyle: {
    width: cellWH,
    marginLeft: vMargin,
    marginTop: hMargin,
    // 文字内容居中对齐
    alignItems: 'center',
  },
  iconStyle: {
    width: 60,
    height: 60,
  },
})

export default Category
